<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>添加素材</title>
    <link rel="stylesheet" href="../assets/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../assets/style/admin.css">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <script src="../common/header.js"></script>
    <!-- 内容主体区域 -->
    <div id="LAY_app_body">
        <div class="layui-fluid">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-card">
                        <div class="layui-card-header">添加素材</div>
                        <div class="layui-card-body">
                            <form class="layui-form" action="">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">素材名</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="name" lay-verify="name" autocomplete="off"
                                                   placeholder="请输入素材名" value="" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">类型</label>
                                    <div class="layui-input-block">
                                        <input type="radio" name="atta" lay-verify="atta" value="1" title="昵称"
                                               lay-filter="type">
                                        <input type="radio" name="atta" lay-verify="atta" value="2" title="头像"
                                               lay-filter="type">
                                        <input type="radio" name="atta" lay-verify="atta" value="3" title="朋友圈背景"
                                               lay-filter="type">
                                        <input type="radio" name="atta" lay-verify="atta" value="4" title="个性签名"
                                               lay-filter="type">
                                        <input type="radio" name="atta" lay-verify="atta" value="5" title="自动回复"
                                               lay-filter="type">
                                        <input type="radio" name="atta" lay-verify="atta" value="6" title="聊天话术"
                                               lay-filter="type">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">分组</label>
                                    <div class="layui-input-inline">
                                        <select id="groupId" name="groupId" lay-verify="groupId"
                                                style="layui-input-inline" onchange="reloadList()">
                                        </select>
                                    </div>
                                </div>
                                <input type="hidden" name="id" value="0">
                                <div class="layui-form-item layui-form-text" id="content_block" style="display: none">
                                    <label class="layui-form-label">内容</label>
                                    <div class="layui-input-block">
                                        <textarea name="content" lay-verify="content" placeholder="请输入内容，不超过2000个字符"
                                                  class="layui-textarea"
                                                  lay-verify="content"></textarea>
                                    </div>
                                </div>
                                <div class="layui-upload" id="image_block" style="display: none">
                                    <label class="layui-form-label">上传图片</label>
                                    <button type="button" class="layui-btn" id="test1">上传图片</button>
                                    (支持jpg|jpeg|png)
                                    <div class="layui-upload-list" id="image_list" style="padding-left: 120px">
                                    </div>
                                    <p id="demoText"></p>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <a class="layui-btn" lay-submit lay-filter="formSubmit">提交</a>
                                        <a class="layui-btn layui-btn-primary" href="material_manage.html">取消</a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        var imgList = []
        layui.use(['form', 'upload'], function () {
            var $ = layui.$
                , form = layui.form
                , upload = layui.upload
                , layer = layui.layer;

            form.verify({
                name: function (value) {
                    if (value.length < 1) {
                        return '请填写素材名'
                    }
                },
                groupId: function (value) {
                    if (value === '0') {
                        return '请选择分组'
                    }
                },
                content: function (value) {
                    var type = $("input[ name='atta' ]:checked ").val();
                    var file_name = $("input[ name=image ]").val();

                    if (type === '1' || type === '4' || type === '5' || type === '6') {
                        if (value.length < 2) {
                            return '内容不能少于2个字符';
                        } else if (value.length > 2000) {
                            return '内容不能超过2000个字符';
                        }
                    } else if (type === '2' || type === '3') {
                        if (!file_name) {
                            return '请上传图片';
                        }
                    } else if (type === undefined) {
                        return '请选择类型';
                    }
                }

            });

            //监听提交
            form.on('submit(formSubmit)', function (data) {
                layer.msg('提交中', {
                    shadeClose: false
                    , icon: 16
                    , shade: 0.01
                });
                if ((data.field.atta === '2' || data.field.atta === '3')) {
                    uploadInst.upload();
                } else {
                    service.post('api/v1/material', {
                        atta: data.field.atta,
                        content: data.field.content,
                        groupId: parseInt(data.field.groupId),
                        name: data.field.name
                    }).then((res) => {
                        if (res.code === 200) {
                            layer.msg('添加成功', {offset: '45vh', icon: 1, time: 2000});
                        } else {
                            layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                        }
                    }).catch((err) => {
                        layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                    })
                }
                return false;
            });

            //普通图片上传
            var uploadInst = upload.render({
                elem: '#test1'
                , url: HOST + 'upload'
                , field: 'image'
                , acceptMime: 'image/jpg, image/png, image/gif, image/jpeg,'
                , accept: 'file' //普通文件
                , auto: false
                , multiple: true
                , bind: '#formSubmit'
                , exts: 'jpg|jpeg|png' //只允许上传图片
                , size: 1024 * 4 //限制文件大小，单位 KB
                , choose: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        var html = '<img class="layui-upload-img" src="' + result + '" style="width: 200px;margin-right: 10px">'
                        $('#image_list').html($('#image_list').html() + html); //图片链接（base64）
                    });
                    imgList = []
                }
                , done: function (res) {
                    if (res.code === 200) {
                        imgList.push(res.data.image_save_url)
                    } else {
                        addImageHiddenField(res.value);
                        $('#demoText').append('<labe>' + res.msg + '</labe>');
                    }
                }
                , allDone: function (obj) { //当文件全部被提交后，才触发
                    service.post('api/v1/material', {
                        atta: $('input[name=atta]').val(),
                        content: JSON.stringify(imgList),
                        groupId: parseInt($('#groupId').val()),
                        name: $('input[name=name]').val()
                    }).then((res) => {
                        if (res.code === 200) {
                            layer.msg('添加成功', {offset: '45vh', icon: 1, time: 2000});
                        } else {
                            layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                        }
                    }).catch((err) => {
                        layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                    })
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });

            var addImageHiddenField = function (value) {
                $('#file_name').val(value);
            };

            form.on('radio(type)', function (data) {
                var type = data.value;
                if (type === '1' || type === '4' || type === '5' || type === '6') {
                    $('#content_block').show();
                    $('#image_block').hide();
                } else {
                    $('#image_block').show();
                    $('#content_block').hide();
                }
                service.post('api/v1/materialgroups', {type: parseInt(type)}).then((res) => {
                    if (res.code === 0) {
                        var html = '<option value="0">选择分组</option>'
                        if (res.data.length > 0) {
                            res.data.forEach(e => {
                                html += '<option value=' + e.id + '>' + e.name + '</option>'
                            })
                        }
                        $('#groupId').html(html)
                        form.render('select')
                    } else {
                        layer.msg(res.msg, {offset: '45vh', icon: 5, time: 2000});
                    }
                }).catch((err) => {
                    layer.msg(err.msg, {offset: '45vh', icon: 5, time: 2000});
                })
            });
        });
    </script>
</div>
</body>
</html>
